//
//  BCAPI.swift
//  NewXueBa
//
//  Created by Shine on 2019/5/30.
//  Copyright © 2019 jmxQAQ. All rights reserved.
//

import Foundation
import Moya

let XueBa_WebSocketURL: String = "172.16.2.17"
let XueBa_WebSocketPort: String = "9669"

let LoadingPlugin = NetworkActivityPlugin { (type, target) in
    guard let vc = topVC else { return }
    switch type {
    case .began:
        MBProgressHUD.hide(for: vc.view, animated: false)
        MBProgressHUD.showAdded(to: vc.view, animated: true)
    case .ended:
        MBProgressHUD.hide(for: vc.view, animated: true)
    }
}

let timeoutClosure = {(endpoint: Endpoint, closure: MoyaProvider<BCAPI>.RequestResultClosure) -> Void in
    
    if var urlRequest = try? endpoint.urlRequest() {
        urlRequest.timeoutInterval = 20
        closure(.success(urlRequest))
    } else {
        closure(.failure(MoyaError.requestMapping(endpoint.url)))
    }
}

/// 关闭https认证
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"172.16.2.17": .disableEvaluation
]
let manager = Manager(
    configuration: URLSessionConfiguration.default,
    serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)

// 没有加载的请求
let ApiProvider = MoyaProvider<BCAPI>(requestClosure: timeoutClosure, manager: manager)
// 有加载plugin的请求
let ApiLoadingProvider = MoyaProvider<BCAPI>(requestClosure: timeoutClosure, manager: manager, plugins: [LoadingPlugin])

enum BCAPI {
    case studyLogin(phone: String, pwd: String, ver: String, ctype: String)
    case get_msg_code(phone: String, verify_code: String, ver: String, ctype: String)// 获取短信验证码
    case code_login(phone: String, verify_code: String, code: String, ver: String, ctype: String)// 短信验证码登录
    case get_user_courses(version: NSInteger)
    case search_pages(version: NSInteger, course_name: String)
    case get_history_page(version: NSInteger) //获取历史元数据
    case get_page_courses(offset: NSInteger, version: NSInteger) //获取历史课程指定页码的课程数据(倒排结构)
    case update_nickname(nickName: String) // 更新昵称
    case upload_photo(iamgeData: Data, fileKey: String) //上传头像
}

extension BCAPI: TargetType {

    //服务器地址
    var baseURL: URL {
        return URL(string: "https://172.16.2.17:9667")!
    }
    //各个请求的具体路径
    var path: String {
        switch self {
        case .studyLogin:
            return "/login"
        case .get_user_courses:
            return "/get_user_courses"
        case .search_pages:
            return "/search_pages"
        case .get_history_page:
            return "/get_history_page"
        case .get_page_courses:
            return "/get_page_courses"
        case .update_nickname:
            return "/update_nickname"
        case .upload_photo:
            return "/upload_photo"
        case .get_msg_code:
            return "/get_msg_code"
        case .code_login:
            return "/code_login"
        }
    }
    
    var method: Alamofire.HTTPMethod {
        switch self {
        case .studyLogin:
            return .get
        default:
            return .post
        }
    }
    //这个就是做单元测试模拟的数据，只会在单元测试文件中有作用
    var sampleData: Data {
        return "".data(using: String.Encoding.utf8)!
    }
    
    //请求任务事件（这里附带上参数）
    var task: Task {
        var parmeters: [String: Any]?
        switch self {
        case .studyLogin(let phone, let pwd, let ver, let ctype):
            parmeters = ["phone": phone, "pwd": pwd, "ver": ver, "ctype": ctype]
            return .requestParameters(parameters: parmeters!, encoding: URLEncoding.default)
        case .get_msg_code(let phone, let verify_code, let ver, let ctype):
            parmeters = ["phone": phone, "verify_code": verify_code, "ver": ver, "ctype": ctype]
            return .requestParameters(parameters: parmeters!, encoding: URLEncoding.default)
        case .code_login(let phone, let verify_code,let code, let ver, let ctype):
            parmeters = ["phone": phone, "verify_code": verify_code, "code": code, "ver": ver, "ctype": ctype]
            return .requestParameters(parameters: parmeters!, encoding: URLEncoding.default)
        case .get_user_courses(let version):
            parmeters = ["version": version]
        case .search_pages(let version, let course_name):
            parmeters = ["version": version, "course_name": course_name]
        case .get_history_page(let version):
            parmeters = ["version": version]
        case .get_page_courses(let offset, let version):
            parmeters = ["version": version, "offset":offset]
        case .update_nickname(let nickName):
            parmeters = ["nick_name": nickName]
        case .upload_photo(let iamgeData, _ ):
            return .requestData(iamgeData)
        }
         return .requestCompositeParameters(bodyParameters: parmeters!, bodyEncoding: JSONEncoding.default, urlParameters: [String: Any]()) //参数放在Body中
        /*
         case requestCompositeData(bodyData: Data, urlParameters: [String: Any])
         case requestData(Data)
         这两个也可以，不过要手动转成JSon再转成Data
         */
    }
    //请求头
    var headers: [String : String]? {
        switch self {
        case .studyLogin, .get_msg_code, .code_login:
            return nil
        case .upload_photo( _ , let fileKey):
            let params = ["ci-token": BCUserManager.shareManager.user_token ?? "",
                          "ci-uid":BCUserManager.shareManager.user_uid ?? "",
                          "Content-Type":"application/json",
                          "X-Key-Filekey":fileKey]
            return params
        default:
            let params = ["ci-token": BCUserManager.shareManager.user_token ?? "",
                          "ci-uid":BCUserManager.shareManager.user_uid ?? "",
                          "Content-Type":"application/json"] // 让请求满足在body中的Raw地方
            return params
        }
    }
    
}

